package com.example.demo33.service;

import com.example.demo33.entity.Item;
import com.example.demo33.entity.SingleGoodResponse;
import com.example.demo33.entity.Stats;
import com.example.demo33.entity.api.GoodIdResponse;
import com.example.demo33.mode.ItemRepository;
import com.example.demo33.mode.UserRepository;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.math.BigDecimal;
import java.util.Optional;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemRepository itemRepository;

    @Autowired
    private UserRepository userRepository; // 需要注入UserRepository用于关联用户

    @Autowired
    private CsqaqApiService csqaqApiService; // 已有的第三方API服务

    // 保存饰品（新增逻辑：填充imgUrl和marketHashName）
    @Override
    public Item saveItem(Item item) {
        try {
            // 1. 获取market_hash_name（从/search-good-id接口的结果中提取）
            // 调用搜索接口，传入goodId对应的饰品名称，获取详情
            GoodIdResponse searchResponse = csqaqApiService.getGoodId(1, 1, item.getName());
            if (searchResponse != null && searchResponse.getCode() == 200
                    && searchResponse.getData() != null && !searchResponse.getData().getData().isEmpty()) {
                // 从搜索结果中找到匹配goodId的项，提取market_hash_name
                var goodsMap = searchResponse.getData().getData();
                var targetGood = goodsMap.values().stream()
                        .filter(good -> good.getId().equals(item.getGoodId()))
                        .findFirst()
                        .orElse(null);
                if (targetGood != null) {
                    item.setMarketHashName(targetGood.getMarket_hash_name());
                }
            }

            // 添加2秒延迟（不推荐的临时方案）
            Thread.sleep(1000);

            // 2. 获取img（调用/good-detail接口）
            SingleGoodResponse detailResponse = csqaqApiService.getSingleGood(item.getGoodId());
            if (detailResponse != null && detailResponse.getCode() == 200
                    && detailResponse.getData() != null && detailResponse.getData().getGoods_info() != null) {
                item.setImgUrl(detailResponse.getData().getGoods_info().getImg());
            }

            // 3. 保存到数据库
            return itemRepository.save(item);
        } catch (Exception e) {
            throw new RuntimeException("保存饰品失败：" + e.getMessage());
        }
    }

    // 查询单个饰品
    @Override
    public Optional<Item> getItemById(Long id) {
        return itemRepository.findById(id);
    }

    // 删除饰品
    @Override
    public void deleteItem(Long id) {
        // 先检查是否存在
        if (!itemRepository.existsById(id)) {
            throw new EntityNotFoundException("饰品不存在，ID: " + id);
        }
        itemRepository.deleteById(id);
    }

    // 按用户ID分页查询
    @Override
    public Page<Item> getItemsByUserId(Long userId, int page, int size,
                                       Optional<String> sort, Optional<String> direction) {
        Sort.Direction sortDirection = direction.map(d ->
                "ASC".equalsIgnoreCase(d) ? Sort.Direction.ASC : Sort.Direction.DESC
        ).orElse(Sort.Direction.DESC);

        String sortField = sort.orElse("buyTime");
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sortField));
        return itemRepository.findByUserId(userId, pageable);
    }

    // 按用户ID和状态查询
    @Override
    public Page<Item> getItemsByUserIdAndStatus(Long userId, String status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "buyTime"));

        switch (status) {
            case "holding":
                return itemRepository.findByUserIdAndHolding(userId, pageable);
            case "partially_sold":
                return itemRepository.findByUserIdAndPartiallySold(userId, pageable);
            case "sold_out":
                return itemRepository.findByUserIdAndSoldOut(userId, pageable);
            default:
                return getItemsByUserId(userId, page, size, Optional.empty(), Optional.empty());
        }
    }

    // 按用户ID和搜索词查询
    @Override
    public Page<Item> getItemsByUserIdAndSearch(
            Long userId,
            int page,
            int size,
            Optional<String> sort,
            Optional<String> direction,
            Optional<String> search
    ) {
        Sort.Direction sortDirection = direction.map(d ->
                "ASC".equalsIgnoreCase(d) ? Sort.Direction.ASC : Sort.Direction.DESC
        ).orElse(Sort.Direction.DESC);

        String sortField = sort.orElse("buyTime");
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sortField));

        if (search.isPresent() && !search.get().trim().isEmpty()) {
            return itemRepository.findByUserIdAndNameContaining(userId, search.get(), pageable);
        } else {
            return itemRepository.findByUserId(userId, pageable);
        }
    }

    // 按用户ID、状态和搜索词查询
    @Override
    public Page<Item> getItemsByUserIdAndStatusAndSearch(
            Long userId,
            String status,
            int page,
            int size,
            Optional<String> search
    ) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "buyTime"));

        // 无搜索词时直接按状态查询
        if (!search.isPresent() || search.get().trim().isEmpty()) {
            return getItemsByUserIdAndStatus(userId, status, page, size);
        }

        // 有搜索词时按状态+搜索词查询
        switch (status) {
            case "holding":
                return itemRepository.findByUserIdAndNameContainingAndHolding(userId, search.get(), pageable);
            case "partially_sold":
                return itemRepository.findByUserIdAndNameContainingAndPartiallySold(userId, search.get(), pageable);
            case "sold_out":
                return itemRepository.findByUserIdAndNameContainingAndSoldOut(userId, search.get(), pageable);
            default:
                return getItemsByUserIdAndSearch(userId, page, size, Optional.of("buyTime"), Optional.of("DESC"), search);
        }
    }

    @Override
    public Stats getUserStats(Long userId) {
        // 计算每件饰品的(总数量 - 已售出数量)之和
        Integer holdingCount = itemRepository.calculateHoldingCount(userId);

        // 计算总售出数量
        Integer totalSoldQuantity = itemRepository.sumSoldQuantityByUserId(userId);

        // 计算总购入成本 (仅包含有售出记录的饰品)
        BigDecimal totalBuyCost = itemRepository.calculateTotalBuyCostForSoldItems(userId);

        // 计算总售出收入
        BigDecimal totalSellRevenue = itemRepository.calculateTotalSellRevenue(userId);

        // 只有当总售出收入不为空时才计算总盈利
        BigDecimal totalProfit = totalSellRevenue != null ?
                totalSellRevenue.subtract(totalBuyCost) :
                BigDecimal.ZERO;

        return new Stats(holdingCount, totalSoldQuantity, totalProfit);
    }
}